
var MousePartyUDPClient = function() {

    var dgram = require('dgram');
    var server = dgram.createSocket("udp4");
    var os = require('os');

    var interfaces = os.networkInterfaces();
    var addresses = [];

//var ServerIP = "10.16.4.135"; // Trocar pelo IP do servidor na rede.
    var ServerIP = getLocalAddress();

    var onmessageCallback = function() {
    };
    var active = false;


    server.on("error", function(err) {
        console.log("server error:\n" + err.stack);
        server.close();
    });

    server.on("message", function(msg, rinfo) {
        //console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port);
        if(rinfo.address !== ServerIP){
            onmessageCallback(msg, rinfo);
        }
//        var message = new Buffer("oi!");
//        server.send(message, 0, message.length, 8039, "230.185.192.108");
    });

    server.on("listening", function() {
        var address = server.address();
        console.log("server listening " + address.address + ":" + address.port);

    });

    server.bind(8039, ServerIP, function() {
        server.setBroadcast(true);
        server.setMulticastTTL(128);
        server.setMulticastLoopback(false);
        server.addMembership('230.185.192.108', ServerIP);
        active = true;
//    var message = new Buffer("alo!");
//    server.send(message, 0, message.length, 8039, "230.185.192.108");
    });



    function getLocalAddress() {
        for (k in interfaces) {
            for (k2 in interfaces[k]) {
                var address = interfaces[k][k2];
                if (address.family == 'IPv4' && !address.internal) {
                    addresses.push(address.address);
                }
            }
        }
        console.log(addresses);

        if (addresses.length === 1) {
            return addresses[0];
        } else {
            return addresses;
        }
    }

    console.log("multicasting");

    this.sendMessage = function(string) {
        if (active) {
            var message = new Buffer(string);
            server.send(message, 0, message.length, 8039, "230.185.192.108");
        }
    };

    this.onMessage = function(callBack) {
        onmessageCallback = callBack;
    };
    
    this.getIP = function(){
        return ServerIP;
    };

};




